import { reqGetCode, reqUserRegister, reqUserLogin, reqGetUserInfo, reqLogout } from '@/api'

export default {

  namespaced: true,

  state: {
    // 服务器响应回来的数据
    code: '',
    token: localStorage.getItem('TOKEN'),
    userInfo: {}

  },

  actions: {
    // 获取验证码
    async getCode({ commit }, phoneNum) {
      const result = await reqGetCode(phoneNum)
      if (result.code === 200) {
        commit('GETCODE', result.data)
        return 'ok'
      } else {
        return Promise.reject(new Error('faile'))
      }
    },
    // 用户注册
    async userRegister(context, user) {
      const result = await reqUserRegister(user)
      if (result.code === 200) {
        return 'ok'
      } else {
        return Promise.reject(new Error('faile'))
      }
    },
    // 用户登录
    async userLogin({ commit }, user) {
      const result = await reqUserLogin(user)
      if (result.code === 200) {
        commit('USERLOGIN', result.data.token)
        localStorage.setItem('TOKEN', result.data.token)
        return 'ok'
      } else {
        return Promise.reject(new Error('faile'))
      }
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
      const result = await reqGetUserInfo()
      if (result.code === 200) {
        commit('GETUSERINFO', result.data)
      }
    },
    async logout({ commit }) {
      const result = await reqLogout()
      if (result.code === 200) {
        commit('CLEAR')
        return 'OK'
      } else {
        return Promise.reject(new Error('faile'))
      }
    }

  },

  mutations: {

    GETCODE(state, code) {
      state.code = code
    },
    USERLOGIN(state, token) {
      state.token = token
    },
    GETUSERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
    CLEAR(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('TOKEN')
    }
  },

  getters: {

  }
}
